package xjay.ai.emotionalsupport.agent;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import xjay.ai.emotionalsupport.chatmemory.ChatHistoryService;
import xjay.ai.emotionalsupport.rag.RagService;
import xjay.ai.emotionalsupport.tools.Markdown2TextTool;
import xjay.ai.emotionalsupport.profile.TarotUserProfileService;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class TarotAgent extends CharacterBaseAgent{







    @Resource
    private TarotUserProfileService tarotUserProfileService;

    public TarotAgent(
            @Qualifier("agentTools") ToolCallback[] agentTools,
            ChatModel qwenChatModel,
            @Qualifier("tarotRag") RagService ragService,
            ChatHistoryService chatHistoryService,
            Markdown2TextTool markdown2TextTool,
            AgentPromptConfig agentPromptConfig) throws IOException {
        super(agentTools); //在CharacterBaseAgent类

        super.setAgentName("TarotAgent"); //BaseAgent


        String SYSTEM_PROMPT = agentPromptConfig.loadAgentPrompt("tarot_system_prompt.md");


        String INSTRUCTION_PROMPT = agentPromptConfig.loadAgentPrompt("tarot_instruction_prompt.md");


        String FINAL_PROMPT = agentPromptConfig.loadAgentPrompt("tarot_final_prompt.md");


        super.setSystemPrompt(SYSTEM_PROMPT);
        super.setInstructionPrompt(INSTRUCTION_PROMPT);
        super.setFinalPrompt(FINAL_PROMPT);
        super.setMaxStep(5);

        //设置历史对话服务
        super.setChatHistoryService(chatHistoryService);

        //设置输出过滤器
        super.setMarkdown2TextTool(markdown2TextTool);

        //STEP:设置rag
        super.setRagService(ragService);
        super.getRagService().loadMarkdown();
        super.getRagService().loadPDF();
        //STEP:设置模型
        QuestionAnswerAdvisor ragAdvisor = QuestionAnswerAdvisor.builder(ragService.rag())
                .build();
        
        ChatClient agentChatClient = ChatClient.builder(qwenChatModel)
                .defaultAdvisors(ragAdvisor)// IMPORTANT: 模型包含rag功能,在这里体现
                .build();
        super.setChatClient(agentChatClient);

    }

    /**
     * note: 冷启动
     * @param userId
     * @param sessionId
     */
    public void warmUp(String userId, String sessionId) {

        log.info("tarotAgent: 冷启动");
        List<Message> historyMessages= super.getChatHistoryService().contextMessages(userId, sessionId);
        if(!historyMessages.isEmpty()){

            // 1) 生成用户画像摘要
            String userProfile = tarotUserProfileService.generateUserProfile(userId, sessionId);

            // 2) 将画像并入系统提示词，使角色设定天然具备用户记忆
            String enrichedSystemPrompt = getSystemPrompt() + "\n\n【用户画像摘要】\n" + userProfile;
            setSystemPrompt(enrichedSystemPrompt);

            log.info("在systemPrompt中注入用户信息摘要：{}", userProfile);
        }

    }

    /**
     *
     * @param userMessage
     * @param userId
     * @param sessionId
     * @return
     */
    public String tarotChat(String userMessage, String userId, String sessionId) {


        String results = super.run(userMessage);

        Prompt prompt = new Prompt(getMessageList(), this.getChatOptions());

        log.info("tarotAgent: 开始回复");

        // STEP:使用SYSTEM_PROMPT + FINAL_PROMPT,将内部分析结果转换为微信聊天风格的回复
        String assistantReply = getChatClient().prompt(prompt)
                .system(getSystemPrompt() + "\n\n" + getFinalPrompt())
                .user(userMessage)
                .call()
                .content();

        if(assistantReply == null || assistantReply.isEmpty()){
            log.error("tarotAgent 回复为空？");
        }
        String reply = super.getMarkdown2TextTool().markdownToText(assistantReply);
        String preview = reply != null && reply.length() > 5 ? reply.substring(0, 5) : reply;
        log.info("tarotAgent: 回复结束，内容为 {} (长度: {})", preview, reply != null ? reply.length() : 0);
        //STEP:数据库持久化，插入一问一答
        super.getChatHistoryService().insertQA(userId, sessionId, userMessage, reply);

        return reply;
    }


    //rag文档删除
    public void deleteDocument(String filename) {
        // 按文件名删除
        getRagService().deleteDocument(filename); //metadata就是一个Map
    }

    // 删除多个文档ID
    public void deleteDocuments(List<String> documentIds) {
        getRagService().deleteDocuments(documentIds);
    }
}
